package br.edu.ufcg.msnlab2.grupo02.booleSimpson;

import br.edu.ufcg.msnlab2.misc.Function;
import br.edu.ufcg.msnlab2.misc.NumericalIntegrationMethod;

public class SimpsonsAlternativeExtendedRule implements NumericalIntegrationMethod {

	private final int numberOfSubintervals;

	public SimpsonsAlternativeExtendedRule() {
		this(2);
	}
	
	public SimpsonsAlternativeExtendedRule( int numberOfSubintervals ) {
		this.numberOfSubintervals = numberOfSubintervals;
	}
	
	@Override
	public double integrate( Function f, double a, double b ) {
		double h = (b-a)/numberOfSubintervals;
		
		double[] coefficients = {17,59,43,49,48,49,43,59,17};
		
		double sum = 0;
		double x = a;
		for ( int i = 0; i < numberOfSubintervals; i++ ) {
			x += h;
			double coefficient;
			if ( i <= 4 ) {
				coefficient = coefficients[i];
			} else if ( i < numberOfSubintervals - 4 ){
				coefficient = coefficients[4];
			} else {
				coefficient = coefficients[ numberOfSubintervals - i + 1 ];
			}
			sum+= coefficient * f.evaluate( x );
		}
		
		return (h/48)*sum;
	}
}
